package com.thientan.controller

import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass

import grails.converters.JSON

import com.thientan.model.ChiTietThuChi
import com.thientan.model.HopDong
import com.thientan.model.ThongKe
import com.thientan.model.enums.LoaiChiTietThuChi
import com.thientan.model.enums.TrangThaiHopDong
import com.thientan.service.ThongKeHopDongService

class ThongKeHopDongController extends AbstractBaseController {
	ThongKeHopDongService thongKeHopDongService

	@Override
	public Class getDomainClass() {
		return ThongKe.class
	}

	@Override
	public String getDomainName() {
		message(code : "default.thientan.messages.thongKe")
	}

	@Override
	public Object getDomainService() {
		return thongKeHopDongService
	}

	@Override
	public String getDisplayFieldName() {
		null
	}

	@Override
	protected String getExportFileName() {
		"ThongKeHopDong"
	}

	protected Map buildExportData(Map exportParams){
		return [data : extractPropertiesAsMaps(ThongKe.listOrderByNgayLap(),
			new DefaultGrailsDomainClass(ThongKe.class).properties*.name, true)]
	}

	private void taoThongKeHopDongMoi() {
		List hdData = HopDong.withCriteria {
			projections {
				property("trangThai")
				count("id")
				sum("giaTri")
				sum("tienGiamGia")
				sum("tienDaThu")
				sum("tienTraTruoc")
			}
			ne("trangThai", TrangThaiHopDong.DONG)
			groupProperty("trangThai")
		}
		Map hdStatus2Amount = [:]
		hdData.each { hdStatus2Amount.put(it[0], it[1]) }

		List thuChiData = ChiTietThuChi.withCriteria {
			projections {
				property("loaiChiTiet")
				sum("soTien")
			}
			ne("loaiChiTiet", LoaiChiTietThuChi.TRA_GOP)
			groupProperty("loaiChiTiet")
		}
		Map ctStatus2Amount = [:]
		thuChiData.each { ctStatus2Amount.put(it[0], it[1]) }

		Double tienKhoThu = ChiTietThuChi.withCriteria {
			createAlias("hopDong", "hd")
			projections { sum("soTien") }
			eq("loaiChiTiet", LoaiChiTietThuChi.DEN_CTY)
			eq("hd.trangThai", TrangThaiHopDong.KHO_THU)
		}.first()
		Double tienDenCtyChiu = ctStatus2Amount.get(LoaiChiTietThuChi.DEN_CTY) ?: 0

		Map thongKeData = [
					"tongSoHd" : hdData.sum {it[1]},
					"tongSoHdThuTienNgay" : hdStatus2Amount.get(TrangThaiHopDong.TIEN_MAT) ?: 0,
					"tongSoHdDangGop" : hdStatus2Amount.get(TrangThaiHopDong.DANG_TRA_GOP) ?: 0,
					"tongSoHdTraHang" : hdStatus2Amount.get(TrangThaiHopDong.TRA_HANG) ?: 0,
					"tongSoHdDenHang" : hdStatus2Amount.get(TrangThaiHopDong.DEN_HANG) ?: 0,
					"tongSoHdKhoThu" : hdStatus2Amount.get(TrangThaiHopDong.KHO_THU) ?: 0,
					"tongSoHdKetThuc" : hdStatus2Amount.get(TrangThaiHopDong.KET_THUC) ?: 0,
					"tongDoanhThuLyThuyet" : hdData.sum {it[2]} ?: 0,
					"tongGiamGia" : hdData.sum {it[3]} ?: 0,
					"tongDenHangCtyChiu" : tienKhoThu ? tienDenCtyChiu - tienKhoThu : tienDenCtyChiu,
					"tongDenHangNvDt" : (ctStatus2Amount.get(LoaiChiTietThuChi.DEN_NV)  ?: 0) + 
										(ctStatus2Amount.get(LoaiChiTietThuChi.DEN_DT) ?: 0),
					"tongKhoThuCtyChiu" : tienKhoThu ?: 0,
					"tongChiPhiTraHang" : ctStatus2Amount.get(LoaiChiTietThuChi.TRA_KHACH) ?: 0,
					"tongKhauHao" : ctStatus2Amount.get(LoaiChiTietThuChi.KHAU_HAO) ?: 0,
					"tongDaThu" : (hdData.sum {it[4]} ?: 0) + (hdData.sum {it[5]} ?: 0)]
		ThongKe thongKe = new ThongKe(thongKeData)
		thongKe.updateDoanhThuThucTe()
		thongKeHopDongService.saveOrUpdate(thongKe)
		if (thongKe.errors.hasErrors()) {
			log.error("Unable to create new statistic", thongKe.errors)
		}
	}

	def xemThongKeHd = {
		Map result = [:]
		try {
			if (!params.boolean("firstLoad")) {
				taoThongKeHopDongMoi()
			}
			Map data = listAsMap(extractPropertiesAsMaps(ThongKe.listOrderByNgayLap(), [
				"ngayLapText",
				"tongSoHd",
				"tongSoHdDangGop",
				"tongSoHdTraHang",
				"tongSoHdDenHang",
				"tongDoanhThuLyThuyet",
				"tongDoanhThuThucTe",
				"tongDaThu",
				"tongPhaiThu"]))
			result = [success : true, data : data]
		} catch (Exception e) {
			log.error("Error occurred when creating statistics: ", e)
			result = [success : false,
						msg : message(code : "default.thientan.messages.unableCreateStatistics", args : null)]
		}
		render result as JSON
	}
}
